package katchup.com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EncodingConverter {
	private static final String UTF_8 = "UTF-8";

	private InputStream inputStream;
	private String charset = null;

	private static final String REGEX = "encoding=\"(.*)\"";
	
	private BufferedReader reader;

	public EncodingConverter(InputStream is) {
		this.inputStream = is;
		reader = new BufferedReader(
				new InputStreamReader(inputStream));
		this.charset = getXMLEncoding();
	}

	private String getXMLEncoding() {
		String encoding = null;
		try {
			reader.mark(10);
			String str = reader.readLine();
			Pattern p = Pattern.compile(REGEX);
			Matcher m = p.matcher(str);
			if (m.find()) {
				encoding = m.group(1);
			}
			reader.reset();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return encoding;
	}

	private String convertUTF8(String str, String charset) {
		try {
			return new String(str.getBytes(charset), UTF_8);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public String convert() {
		StringBuffer sb = new StringBuffer();
		try {
			String s;
			while((s=reader.readLine())!= null){
				sb.append(s).append('\n');
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return convertUTF8(sb.toString(), charset);
	}
}
